/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package diet.controller;

import diet.XMLUtils.Foods;
import diet.XMLUtils.JAXB;
import diet.XMLUtils.XMLUltis;
import diet.dto.FoodDTO;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

/**
 *
 * @author Vrety
 */
public class AjaxStoreFoodServlet extends HttpServlet {

    private JAXB jaxb = null;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String imageURL = request.getParameter("imageURL");
            String foodID = request.getParameter("foodID");
            String isEssential = request.getParameter("isEssential");

            List<FoodDTO> foodEssential = null;
            List<FoodDTO> foodNoEssential = null;
            HttpSession session = request.getSession();
            foodEssential = (List<FoodDTO>) session.getAttribute("foodEssential");
            foodNoEssential = (List<FoodDTO>) session.getAttribute("foodNoEssential");
            if (foodEssential == null) {
                foodEssential = new ArrayList<FoodDTO>();
            }
            if (foodNoEssential == null) {
                foodNoEssential = new ArrayList<FoodDTO>();
            }
            if (isEssential.equals("foodEssential")) {
                //Get xmlString in session

                FoodDTO food = new FoodDTO();
                food.setFoodID(Integer.parseInt(foodID));
                food.setImageURL(imageURL);
                if (foodEssential.isEmpty()) {
                    foodEssential.add(food);
                } else {
                    Boolean isHas = false;
                    for (Iterator<FoodDTO> it = foodEssential.iterator(); it.hasNext();) {
                        FoodDTO foodDTO = it.next();
                        if (foodDTO.getImageURL().equals(food.getImageURL())) {
                            isHas = true;
                            break;
                        }
                    }
                    if(!isHas) {
                        foodEssential.add(food);
                    }


                }
                for (Iterator<FoodDTO> it = foodNoEssential.iterator(); it.hasNext();) {
                    FoodDTO foodDTO = it.next();
                    if (foodDTO.getImageURL().equals(food.getImageURL())) {
                        it.remove();
                        break;
                    }
                }

            } else if (isEssential.equals("foodNoEssential")) {
                FoodDTO food = new FoodDTO();
                food.setFoodID(Integer.parseInt(foodID));
                food.setImageURL(imageURL);
                if (foodNoEssential.isEmpty()) {
                    foodNoEssential.add(food);
                } else {
                     Boolean isHas = false;
                    for (Iterator<FoodDTO> it = foodNoEssential.iterator(); it.hasNext();) {
                        FoodDTO foodDTO = it.next();
                        if (foodDTO.getImageURL().equals(food.getImageURL())) {
                            isHas = true;
                            break;
                        }
                    }
                     if(!isHas){
                         foodNoEssential.add(food);
                     }
                }
                for (Iterator<FoodDTO> it = foodEssential.iterator(); it.hasNext();) {
                    FoodDTO foodDTO = it.next();
                    if (foodDTO.getImageURL().equals(food.getImageURL())) {
                        it.remove();
                        break;
                    }

                }
            }


            //Parse it to xml source and set for listFood
//            JAXBContext jc = JAXBContext.newInstance(Foods.class);
//            Unmarshaller u = jc.createUnmarshaller();
//            StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
//            JAXBElement<Foods> je = u.unmarshal(xmlSource, Foods.class);
//            Foods results = je.getValue();

            //Add more food and save to session


            //use session to save store Food
            session.setAttribute("foodEssential", foodEssential);
            session.setAttribute("foodNoEssential", foodNoEssential);
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
           // response.getWriter().write("You searched: ");
            response.sendRedirect("cooking.jsp");

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
